package com.zqxq.lottery.api.controller;

import com.zqxq.common.constant.Result;
import com.zqxq.lottery.api.feign.FileServerFeignClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Api(value = "文件接口",tags = "文件接口")
@RestController
@Slf4j
@RequestMapping(value = "/file", produces = "application/json")
public class FileController {

    @Autowired
    private FileServerFeignClient fileServerFeignClient;

    @PostMapping("/upload")
    @ApiOperation(value="文件上传", notes="文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "File")
    })
    public Result fileUpload(MultipartFile file){
        Map<String, File> fileMap = new HashMap<>();
        String fileName = file.getOriginalFilename();
        File files = null;
        try {
            files=File.createTempFile("tmp", null);
            file.transferTo(files);
            files.deleteOnExit();
        } catch (HttpException e) {
            e.printStackTrace();
            log.error("fileUpload HttpException",e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IOException HttpException",e);
        }
        fileMap.put("image_ref1",files);
        Result result = fileServerFeignClient.fileUpload(fileMap ,fileName, "ZQXQ-LOTTERY", "image/user", "public");
        return result;
    }

    @PostMapping("/upload/head")
    @ApiOperation(value="文件上传", notes="文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片文件", required = true, dataType = "File")
    })
    public Result fileUploadHead(MultipartFile file){
        Map<String, File> fileMap = new HashMap<>();
        String fileName = file.getOriginalFilename();
        File files = null;
        try {
            files=File.createTempFile("tmp", null);
            file.transferTo(files);
            files.deleteOnExit();
        } catch (HttpException e) {
            e.printStackTrace();
            log.error("fileUpload HttpException",e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IOException HttpException",e);
        }
        fileMap.put("image_ref1",files);
        Result result = fileServerFeignClient.fileUpload(fileMap ,fileName, "ZQXQ-LOTTERY", "image/user/head", "public");
        return result;
    }

}
